package uk.gov.swmprobation.cplite;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.google.analytics.tracking.android.EasyTracker;
import com.google.analytics.tracking.android.MapBuilder;

import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.util.Log;

public class SendWaiting extends IntentService {

	private static final int MAX_PHOTO_DIMENSION =1024;
	private static final int PHOTO_COMPRESSION = 100;
	private Bitmap myBitmap;
	private byte[] imageBytes;
	
	public SendWaiting() {
		super("SendWaiting");
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		int localId = intent.getExtras().getInt("localId");
        DatabaseHandler.getInstance(this);
		Project project = DatabaseHandler.getProject(localId);
		if (PhotoTools.photoExists(project.getImagePath())) {
			SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
			String prefUserCode = sharedPref.getString("pref_user_code", "General Public");
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost("http://cpvisibility.org/geovation/save.xql");
			try {
			  MultipartEntity entity = new MultipartEntity();
			  	myBitmap = PhotoTools.fitBitmapIn(project.getImagePath(), MAX_PHOTO_DIMENSION);
		        ByteArrayOutputStream baos = new ByteArrayOutputStream();
		        myBitmap.compress(Bitmap.CompressFormat.JPEG, PHOTO_COMPRESSION, baos);
		        imageBytes = baos.toByteArray();
			  String deviceId = Settings.Secure.getString(getContentResolver(),
				         Settings.Secure.ANDROID_ID);
			  entity.addPart("group", new StringBody(deviceId));
			  entity.addPart("lat", new StringBody(Double.toString(project.getLat())));
			  entity.addPart("usercode",new StringBody(prefUserCode));
			  entity.addPart("lng", new StringBody(Double.toString(project.getLng())));
			  entity.addPart("image", new ByteArrayBody(imageBytes,"image.jpg"));
			  entity.addPart("email", new StringBody(sharedPref.getString("user_email", "")));
			  entity.addPart("original_lat", new StringBody(Double.toString(project.getOldLat())));
			  entity.addPart("original_lng", new StringBody(Double.toString(project.getOldLng())));
			  httppost.setEntity(entity);
			  HttpResponse response = httpclient.execute(httppost);
			  String responseString = ResponceBody.getResponseBody(response);
				Document responseDoc = XMLfunctions.XMLfromString(responseString);
				NodeList nodes = responseDoc.getElementsByTagName("document");
				int ProjectID = 0;
				for (int i = 0; i < nodes.getLength(); i++) {
					Element e = (Element)nodes.item(i);
					ProjectID = Integer.parseInt(XMLfunctions.getValue(e, "id"));
					project.setProjectId(ProjectID);
					String ProjectName = XMLfunctions.getValue(e, "title");
					project.setProjectName(ProjectName);
					String Trust = XMLfunctions.getValue(e, "county");
					project.setTrust(Trust);
					createNotification(ProjectID,ProjectName,Trust);
					galleryAddPic(project.getImagePath());
					Log.e("Path",project.getImagePath());
				}
				project.setProjectType(Project.TYPE_MINE);
				project.setProjectStatus("new");
				project.setUpdated(true);
				project.save();
				
				EasyTracker easyTracker = EasyTracker.getInstance(this);
				
				easyTracker.send(MapBuilder
		    		      .createEvent("service_action",     // Event category (required)
		    		                   "project_recieved",  // Event action (required)
		    		                   null,   // Event label
		    		                   null)            // Event value
		    		      .build()
		    		  );
				
				Intent broadcastIntent = new Intent("uk.gov.swmprobation.cpvisibility.event.updatemain");
				sendOrderedBroadcast(broadcastIntent, null);
			} catch (ClientProtocolException e) {
				//TODO 
			} catch (IOException e) {
				//TODO
			}
		} else {
			project.setProjectStatus(Project.TYPE_NAMES[Project.TYPE_DRAFT]);
			project.save();
			Intent broadcastIntent = new Intent("uk.gov.swmprobation.cpvisibility.event.updatemain");
			sendOrderedBroadcast(broadcastIntent, null);
		}
	}
	
	private void createNotification(int projectid,String projectName,String Trust){
		
		String contentText = Helper.shortName(projectName)+" has been submitted to "+Trust+".";;
		String contentTitle = "Project Submitted";
				
		NotificationCompat.Builder mBuilder =
				new NotificationCompat.Builder(this)
				.setAutoCancel(true)
				.setSmallIcon(R.drawable.ic_launcher)	
				.setContentText(contentText)
				.setContentTitle(contentTitle);
				//Creates an explicit intent for an Activity in your app
				Intent resultIntent = new Intent(this, ReviewProjects.class);
				resultIntent.putExtra("project_id", projectid);
				resultIntent.putExtra("updated", true);

				//The stack builder object will contain an artificial back stack for the
				//started Activity.
				//This ensures that navigating backward from the Activity leads out of
				//your application to the Home screen.
				TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
				//Adds the back stack for the Intent (but not the Intent itself)
				stackBuilder.addParentStack(MainActivity.class);
				//Adds the Intent that starts the Activity to the top of the stack
				stackBuilder.addNextIntent(resultIntent);
				PendingIntent resultPendingIntent =
				stackBuilder.getPendingIntent(
				    0,
				    PendingIntent.FLAG_UPDATE_CURRENT
				);
				mBuilder.setContentIntent(resultPendingIntent);
				NotificationManager mNotificationManager =
				(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
				//mId allows you to update the notification later on.
				mNotificationManager.notify(projectid, mBuilder.build());
	}
	
	private void galleryAddPic(String photoPath) {
	    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
	    File f = new File(photoPath);
	    Uri contentUri = Uri.fromFile(f);
	    mediaScanIntent.setData(contentUri);
	    this.sendBroadcast(mediaScanIntent);
	}
	
}
